package com.redpack.redpost.struts.form;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import com.redpack.redpost.util.to.UserLoginAdmin;

public class accessAdmin extends ActionForm {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private String usr;
    private String pass;
    
	public String getUsr() {
		return usr;
	}
	public void setUsr(String usr) {
		this.usr = usr;
	}
	public String getPass() {
		return pass;
	}
	public void setPass(String pass) {
		this.pass = pass;
	}	
    
	public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
		
		ActionErrors errors = new ActionErrors( );
		
		HttpSession session = request.getSession();
		
		String salir = "0";
		if( request.getParameter("salir") != null ){
			salir = request.getParameter("salir");
			request.getSession().removeAttribute("UserLogin");
		}
		
		if( salir.equals("1") ){
			session.removeAttribute("UserLogin");
			request.getSession().removeAttribute("UserLogin");
		}
		
		if ( usr == null || usr.trim().length() == 0 ) {
            errors.add("NombreVacio", new ActionMessage("com.redpack.redpost.web.errors.modules.acceso.usr"));
        }else
            if ( pass == null || pass.trim( ).length( ) == 0 ) {
                errors.add("PassVacio", new ActionMessage("com.redpack.redpost.web.errors.modules.acceso.pwd"));
            }
		
		//revisa si hay errores
        if ( errors.size() > 0 )
        	return errors ;
        
        try {
        	
        	UserLoginAdmin userLogin = new UserLoginAdmin(usr, pass) ;
        	
        	// revisa si coinciden las contrasenias
        	boolean res = userLogin.login( ) ;
        	
        	// en caso de falso
        	if (!res) {
        		errors.add("UserPassIncorrect", new ActionMessage("com.redpack.redpost.web.errors.modules.acceso.no"));
        	} else {
        		int tipousuario = userLogin.getTipousuario();
        		request.getSession().setAttribute("UserLogin", userLogin);
        		request.getSession().setAttribute("tipousuario", ""+tipousuario);
        		
        	}
        		
        	
        } catch (Exception e) {
			e.printStackTrace();
		}
		
		return errors ;
		
	}

}
